from collections import deque
import globalvar
import win32com.client
import tempfile
import os
class RingBuffer(deque):
    def __init__(self, size):
        deque.__init__(self)
        self.size = size
        self.mydict={}
            
    def full_append(self, key,value):
        globalvar.utf8mutex.acquire()
        deque.append(self, key)
        self.mydict[key] = value
        # full, pop the oldest item, left most item
        mypop = self.popleft()
        # remove the dict
        del self.mydict[mypop]
        globalvar.databaselogging.debug("delete the  key in the dict = %s"%(mypop))

        globalvar.utf8mutex.release()
        
    def append(self, key,value):
        globalvar.utf8mutex.acquire()

        deque.append(self, key)
        self.mydict[key] = value

    # max size reached, append becomes full_append
        if len(self) == self.size:
            self.append = self.full_append
        globalvar.utf8mutex.release()            
        
    def getutf8(self,key,value):
        if key in self.mydict.keys():
            
            globalvar.databaselogging.debug("utf8 key in the dict = %s"%(key))
            rtfvalue =  self.mydict[key]
            globalvar.databaselogging.debug("rtfvalue = %s"%(rtfvalue))
                        
        else:
            
            globalvar.databaselogging.debug("utf8 not key in the dict = %s"%(key))
            
            # Get the rtf value
            temppath = tempfile.mktemp(suffix='.rtf')
            fdoc = open(temppath,'w')
            fdoc.write(value)
            fdoc.close()
             
            app = win32com.client.Dispatch('Word.Application')
            app.Visible=0
            doc = app.Documents.Open(temppath)
            str1=doc.Content.Text        
    #        doc.close()
            wc = win32com.client.constants
    
            app.Documents.Close()
            app.Quit()
            os.remove(temppath)
            rtfvalue = str1.encode('utf-8')
            self.append(key,rtfvalue)
            globalvar.databaselogging.debug("rtfvalue = %s"%(rtfvalue))

        return rtfvalue
    
